package com.africanmoviesmobile.ui;

import java.io.IOException;

import org.pixmob.httpclient.HttpClientException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.africanmoviesmobile.R;
import com.africanmoviesmobile.webservice.AmmWebService;
import com.africanmoviesmobile.webservice.BasicAsyncCallback;
import com.africanmoviesmobile.webservice.WebServiceException;

public class AboutActivity extends BaseActivity {

	AmmWebService mAmmWebService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.about_activity);
		
		mAmmWebService = AmmWebService.getInstance(this);
		
		TextView appVersion = (TextView) findViewById(R.id.app_version);
		appVersion.setText(APP_VERSION);
		
		View tokenPricingLink = (View) findViewById(R.id.token_pricing_link);
		tokenPricingLink.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(BUT_TOKEN_URL));
				startActivity(browserIntent);
			}
		});
		
		View legalInformationLink = (View) findViewById(R.id.legal_information_link);
		legalInformationLink.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(TOS_URL));
				startActivity(browserIntent);
			}
		});
		
		View feedbackLink = (View) findViewById(R.id.feedback_link);
		feedbackLink.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", APP_SUPPORT_EMAIL, null));
				emailIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_email_subject));
				startActivity(Intent.createChooser(emailIntent, getResources().getString(R.string.app_email_subject)));
			}
		});
		
		View updateAccountLink = (View) findViewById(R.id.update_account_link);
		updateAccountLink.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				UpdateUserDialogFragment updateUserDialogFragment = new UpdateUserDialogFragment();
				updateUserDialogFragment.setRetainInstance(true);
				updateUserDialogFragment.show(getSupportFragmentManager(), "update_user");			
			}
		});
		
		TextView signOutLinkText = (TextView) findViewById(R.id.sign_out_link_text);
		signOutLinkText.setText(String.format(getResources().getString(R.string.sign_out_with_name), getLoginName()));
		
		View signOutLink = (View) findViewById(R.id.sign_out_link);
		signOutLink.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				logout();
			}
		});
		
	}
	
	 @SuppressLint("ValidFragment")
		public class UpdateUserDialogFragment extends DialogFragment {
	        @Override
	        public Dialog onCreateDialog(Bundle savedInstanceState) {
	            
	        	final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
	            
	            LayoutInflater inflater = getActivity().getLayoutInflater();
	            View updateUserLayout = inflater.inflate(R.layout.update_user, null);
	            
	            final TextView fullNameTextView = (TextView) updateUserLayout.findViewById(R.id.full_name);
	            final TextView oldPasswordTextView = (TextView) updateUserLayout.findViewById(R.id.old_password);
	            final TextView passwordTextView = (TextView) updateUserLayout.findViewById(R.id.password);
	            final TextView retypePasswordTextView = (TextView) updateUserLayout.findViewById(R.id.retype_password);
	            
	            builder.setView(updateUserLayout)
        	   		   .setTitle(R.string.update_account)
	            	   .setPositiveButton(R.string.update, null)
		               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
	                       public void onClick(DialogInterface dialog, int id) {
	                    	   UpdateUserDialogFragment.this.getDialog().cancel();
	                       }
	                   });
	            
	            AlertDialog dialog = builder.create();
	            
	            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
				    @Override
				    public void onShow(final DialogInterface dialog) {
				        Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
				        button.setOnClickListener(new View.OnClickListener() {
				            @Override
				            public void onClick(View view) {
				            	
				            	//if we are updating password
				            	if ((oldPasswordTextView.length() > 0)) {
				            		
				            		mAmmWebService.authenticateUser(getLoginEmail(), oldPasswordTextView.getText().toString(), new BasicAsyncCallback() {

				        				public void onComplete(final boolean[] result, final Object state) {

				        					boolean response = (boolean) result[0];
				        					
				        					if(response){
				        						
				        						runOnUiThread(new Runnable() {public void run() { 
				        							
				        						if((fullNameTextView.length() == 0) || (!fullNameTextView.getText().toString().matches("[a-zA-Z ]+"))){
								            		fullNameTextView.setError(getResources().getString(R.string.invalid_name));
						                   			}else if ((passwordTextView.length() == 0)) {
															passwordTextView.setError(getResources().getString(R.string.invalid_password));
														}else if (passwordTextView.getText().toString().compareToIgnoreCase(retypePasswordTextView.getText().toString()) != 0) {
															retypePasswordTextView.setError(getResources().getString(R.string.retype_new_password_unmatched));
														}else{
															
						        							//update user session
						        							SharedPreferences.Editor editor = mPrefsUserLogin.edit();
						        						    editor.putString("name", fullNameTextView.getText().toString());
						        						    editor.commit();
															
						        						    updateUserInfo(getLoginEmail(), passwordTextView.getText().toString(), fullNameTextView.getText().toString());
						        						    	        								
						        							dialog.dismiss();
						        							
						        							toastMessage(R.string.update_successful);
						        							
						        							Intent intent = getIntent();
						        							intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						        						    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						        						    finish();
						        						    
						        						    startActivity(intent);						        						    
						                   			}
				        						
				        						}});
				        						
				        					}else{
				        						toastMessage(R.string.old_password_unmatched);
				        					}
				        				}

				        				public void onHttpClientException(final HttpClientException e, final Object state) {
				        					Log.w("AMM HttpClientException:", e.getMessage());
				        				}
				        				
				        				public void onIOException(final IOException e, final Object state) {
				        					Log.w("AMM IOException:", e.getMessage());
				        				}

				        				public void onWebServiceException(final WebServiceException e, final Object state) {
				        					Log.w("AMM WebServiceException:", e.getMessage());
				        				}

				        			}, null);
								}else{
									
									if((fullNameTextView.length() == 0) || (!fullNameTextView.getText().toString().matches("[a-zA-Z ]+"))){
					            		fullNameTextView.setError(getResources().getString(R.string.invalid_name));
			                   			}else{
												
			        							//update user session
			        							SharedPreferences.Editor editor = mPrefsUserLogin.edit();
			        						    editor.putString("name", fullNameTextView.getText().toString());
			        						    editor.commit();
												
			        						    updateUserInfo(getLoginEmail(), null, fullNameTextView.getText().toString());
			        						    	        								
			        							dialog.dismiss();
			        							
			        							toastMessage(R.string.update_successful);
			        							
			        							Intent intent = getIntent();
			        							intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			        						    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			        						    finish();
			        						    
			        						    startActivity(intent);
			                   			}
								}
				            }
				        });
				    }
				});
	            
	            return dialog;
	        }
	    }
	
}
